const { db } = require('../config/database');

class Diary {
  // 创建日记
  static create(user_id, title, content, mood, tags = '[]', media = '[]') {
    return new Promise((resolve, reject) => {
      const stmt = db.prepare('INSERT INTO diaries (user_id, title, content, mood, tags, media) VALUES (?, ?, ?, ?, ?, ?)');
      stmt.run(user_id, title, content, mood, tags, media, function(err) {
        if (err) {
          reject(err);
        } else {
          resolve({
            id: this.lastID,
            user_id,
            title,
            content,
            mood,
            tags: JSON.parse(tags),
            media: JSON.parse(media),
            created_at: new Date().toISOString()
          });
        }
      });
      stmt.finalize();
    });
  }

  // 根据ID查找日记
  static findById(id) {
    return new Promise((resolve, reject) => {
      db.get('SELECT * FROM diaries WHERE id = ?', [id], (err, row) => {
        if (err) {
          reject(err);
        } else {
          if (row) {
            // 解析JSON字段
            row.tags = JSON.parse(row.tags || '[]');
            row.media = JSON.parse(row.media || '[]');
          }
          resolve(row);
        }
      });
    });
  }

  // 根据用户ID查找所有日记
  static findByUserId(user_id) {
    return new Promise((resolve, reject) => {
      db.all('SELECT * FROM diaries WHERE user_id = ? ORDER BY created_at DESC', [user_id], (err, rows) => {
        if (err) {
          reject(err);
        } else {
          // 解析JSON字段
          rows = rows.map(row => {
            row.tags = JSON.parse(row.tags || '[]');
            row.media = JSON.parse(row.media || '[]');
            return row;
          });
          resolve(rows);
        }
      });
    });
  }

  // 更新日记
  static update(id, title, content, mood, tags = '[]', media = '[]') {
    return new Promise((resolve, reject) => {
      const stmt = db.prepare('UPDATE diaries SET title = ?, content = ?, mood = ?, tags = ?, media = ? WHERE id = ?');
      stmt.run(title, content, mood, tags, media, id, function(err) {
        if (err) {
          reject(err);
        } else {
          resolve({
            id,
            title,
            content,
            mood,
            tags: JSON.parse(tags),
            media: JSON.parse(media)
          });
        }
      });
      stmt.finalize();
    });
  }

  // 删除日记
  static delete(id) {
    return new Promise((resolve, reject) => {
      const stmt = db.prepare('DELETE FROM diaries WHERE id = ?');
      stmt.run(id, function(err) {
        if (err) {
          reject(err);
        } else {
          resolve({ id });
        }
      });
      stmt.finalize();
    });
  }
}

module.exports = Diary;